// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Bird from "./bird";
import store, { GAME_STATE } from "./common";
import PipeGroupManager from "./pipe_group_manager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Node)
    bird: cc.Node = null;

    @property(cc.Label)
    score: cc.Label = null;

    @property(cc.Node)
    game_over: cc.Node = null;

    @property(cc.Node)
    btn_restart: cc.Node = null;

    @property(cc.Label)
    game_over_score: cc.Label = null;

    @property(cc.AudioClip)
    bgmClip: cc.AudioClip = null;

    @property(cc.AudioClip)
    gameOverSoundClip: cc.AudioClip = null;

    @property(cc.AudioClip)
    scoreSoundClip: cc.AudioClip = null;

    @property(cc.AudioClip)
    deadSoundClip: cc.AudioClip = null;

    private bgmAudioId: number;

    onLoad() {

        store.score = 0;
        store.state = GAME_STATE.IDLE;

        this.game_over.active = false;
        this.score.node.active = false;

        this.btn_restart.on(cc.Node.EventType.TOUCH_START, this.restartGame, this);

        const manager = cc.director.getCollisionManager();
        manager.enabled = true;
    }

    start() {
        this.startGame();
    }

    // 开始游戏
    startGame() {
        this.game_over.active = false;
        this.score.node.active = true;
        store.score = 0;
        store.pipeManager.startSpawn();
        store.state = GAME_STATE.GAMING;
        this.bird.getComponent(Bird).startFly();

        this.bgmAudioId = cc.audioEngine.play(this.bgmClip, false, 0.3);
    }

    gameOver() {
        this.game_over_score.string = 'Score:' + store.score;
        this.game_over.active = true;
        this.score.node.active = false;
        this.bird.getComponent(Bird).stopFly();
        cc.audioEngine.stop(this.bgmAudioId);
        cc.audioEngine.play(this.deadSoundClip, false, 1);
        cc.audioEngine.play(this.gameOverSoundClip, false, 1);

        store.state = GAME_STATE.OVER;
        store.pipeManager.reset();
    }

    restartGame() {
        cc.director.loadScene('Game');
    }

    gainScore() {
        store.score += 1;
        this.score.string = 'Score:' + store.score;
        cc.audioEngine.play(this.scoreSoundClip, false, 1);
    }
}
